using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Net;
using System.ComponentModel;
using TwitterLib;

namespace Pawing.Controls.Search
{
    public class TwitterSearchService : ITwitterSearchService
    {
        public void BeginSearch(SearchItem item)
        {                        
            var worker = new BackgroundWorker();
            worker.RunWorkerCompleted += (s,e) =>
            {
                try
                {
                    if (e.Result != null)
                    {
                        OnSearchComplete(e.Result as IEnumerable<SearchResult>);
                    }
                }
                catch(WebException ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            };
            worker.DoWork += (s, e) =>
            {
                //var client = new WebClient();
                //var uri = new Uri(e.Argument.ToString());
                //var xml = client.DownloadString(uri);
                //if (!String.IsNullOrEmpty(xml))
                //{
                //    e.Result = ParseResults(xml, item);
                //}
                TwitterNet twitter = new TwitterNet();
                twitter.AccessToken = Properties.Settings.Default.OAuthToken;
                twitter.AccessTokenSecret = Properties.Settings.Default.OAuthTokenSecret;
                if (item.SearchType == SearchType.User)
                {
                    e.Result = ConvertToSearchResult(twitter.SearchUsers(item.Phrase), item);
                }
                else
                {
                    e.Result = ConvertToSearchResult(twitter.SearchStatuses(item.Phrase), item);
                }
            };

            //string url = String.Format(urlFormat, Uri.EscapeUriString(item.Phrase));
            worker.RunWorkerAsync(item.Phrase);
        }

        private IEnumerable<SearchResult> ConvertToSearchResult(UserCollection _userCollection,SearchItem _item)
        {
            //foreach (User user in userCollection)
            //{
            //    searchResult.
            //}
            return _userCollection.Select(e => ToSearchResult(e,_item));
        }

        private IEnumerable<SearchResult> ConvertToSearchResult(TweetCollection _tweetCollection, SearchItem _item)
        {
            return _tweetCollection.Select(e => ToSearchResult(e, _item));
        }

        private SearchResult ToSearchResult(Tweet _tweet, SearchItem _item)
        {
            var result = new SearchResult
            {
                AssociatedSearchItem = _item,
                Text = _tweet.Text,
                Source=_tweet.Source,
                User = _tweet.User
            };
            result.AssociatedSearchItem = _item;
            return result;
        }

        private SearchResult ToSearchResult(User _user, SearchItem _item)
        {
            var result = new SearchResult
            {
                AssociatedSearchItem = _item,
                Text = _user.Tweet.Text,
                SourceWithOutUrl = _user.Location,
                User = _user,                 
            };
            result.AssociatedSearchItem = _item;
            return result;
        }

        private IEnumerable<SearchResult> ParseResults(string xml, SearchItem item)
        {
            var doc = XDocument.Parse(xml);
            var converter = new TwitterSearchAtomConverter(doc, item);
            return converter.Convert();
        }

        private void OnSearchComplete(IEnumerable<SearchResult> results)
        {
            var handler = SearchComplete;
            if(handler != null && results != null && results.Any())
            {
                var args = new SearchCompleteEventArgs();
                args.Results = results.ToList();
                handler(this, args);
            }
        }

        public event EventHandler<SearchCompleteEventArgs> SearchComplete;

    }
}
